package mq

import (
	"gitee.com/alex_li/rodinbell/etc"
	"github.com/lishimeng/go-connector/mqtt"
	"github.com/lishimeng/go-log"
	"time"
)

var Session *Connector
var Usable bool

func enableIot() (c *Connector, err error){

	log.Info("enable iot")
	var b = etc.Config.Mq.Broker
	if len(b) == 0 {
		b = "tcp://127.0.0.1:1883"
	}

	c, err = New(b, etc.Config.Name, "rfid/data", func(_ mqtt.Session) {
		Usable = true
	}, func(_ mqtt.Session, _ error) {
		Usable = false
	})
	return
}

func StartIot() {
	go func() {
		for {
			var fail error
			Session, fail = enableIot()
			if fail == nil {
				log.Info("iot connect success")
				return
			} else {
				log.Info("iot connect fail")
				log.Info(fail)
				time.Sleep(3*time.Second)
			}
		}
	}()
	return
}
